package com.xizi.java8;

import org.junit.Test;

import java.util.Arrays;
import java.util.Collections;
import java.util.List;

/**
 * @author xizizzz
 * @description: TODO
 * @date 2021-7-15下午 04:35
 */
public class TestLambda {

    List<Employee> emps = Arrays.asList(
            new Employee(101, "Z3", 19, 9999.99),
            new Employee(102, "L4", 20, 7777.77),
            new Employee(103, "W5", 35, 6666.66),
            new Employee(104, "Tom", 44, 1111.11),
            new Employee(105, "Jerry", 60, 4444.44)
    );

    //调用 Collections.sort() 方法，通过定制排序 比较两个 Employee (先按照年龄比，年龄相同按照姓名比)
    // 使用 Lambda 表达式作为参数传递
    @Test
    public void test01() {
        Collections.sort(emps, (e1, e2) -> {
            if (e1.getAge() == e2.getAge()) {
                return e1.getName().compareTo(e2.getName());
            } else {
                return Integer.compare(e1.getAge(), e2.getAge());
            }
        });
        for (Employee emp : emps) {
            System.out.println(emp);
        }
    }

    //声明函数式接口，接口中声明抽象方法，String getValue(String str)
    @Test
    public void test2() {
        String trimStr = strHandler("\t\t\t xizizzz   ", (str) -> str.trim());
        System.out.println(trimStr);

        String upper = strHandler("xizizzz", (str) -> str.toUpperCase());
        System.out.println(upper);

        String newStr = strHandler("xizizzz", (str) -> str.substring(2, 5));
        System.out.println(newStr);
    }

    //需求：用于处理字符串
    public String strHandler(String str, MyFunction mf) {
        return mf.getValue(str);
    }

    // 声明一个带两个泛型的函数式接口，泛型类型为<T, R> T 为参数，R 为返回值
    @Test
    public void test3() {
        op(100L, 200L, (x, y) -> x + y);

        op(100L, 200L, (x, y) -> x * y);
    }

    //需求：对于两个 Long 型数据进行处理
    public void op(Long l1, Long l2, MyFunction2<Long, Long> mf) {
        System.out.println(mf.getValue(l1, l2));
    }

}
